package controllers;

import play.*;
import play.mvc.*;
import play.data.*;
import java.util.*;
import java.io.*;
import javax.persistence.Query;
import models.*;
import play.db.jpa.JPA;

import utils.*;


/**
 * Manage Documents related operations.
 */

public class Documents extends Controller {
  
    public static void index() {
        render();
    }

    /**
     * Get documents json.
     */
    public static void json(int page, int pagesize) {   	
    	List<Document> list = Document.all().fetch(page, pagesize);          
        long total = Document.count();
        
        String documentsStr = Document.toJson(list);
        String jsonStr = YUtils.ligerGridData(documentsStr, total);
        
        renderJSON(jsonStr);
    }

    /**
     * Add a Document.
     */
    public static void add(Document Document) {     
       
    }

    /**
     * Get documents json.
     */
    public static void findAll() {
        List<Document> documents = Document.findAll();
        renderJSON(documents);
    }

    static User connectedUser() {
        String userId = session.get("logged");
        return (userId==null) ? null : (User)User.findById(Long.parseLong(userId));
    }

    /**
     * Update a Document.
     */
    public static void save(Document document) {
        if (document.id == null) {
            document.creator = connectedUser();
            document.createTime = new Date();
        }

        document.updateTime = new Date();    
        document.save();
        renderJSON("");
    }
    
    /**
     * Delete a Document.
     */
    public static void delete(long id) {
        Document.findById(id)._delete();
        renderJSON("");
    }
  
}

